package com.neudu.yiyang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.mapper.BedMapper;
import com.neudu.yiyang.mapper.BeddetailsMapper;
import com.neudu.yiyang.mapper.CustomerMapper;
import com.neudu.yiyang.pojo.Bed;
import com.neudu.yiyang.pojo.Beddetails;
import com.neudu.yiyang.pojo.Customer;
import com.neudu.yiyang.service.BeddetailsService;
import com.neudu.yiyang.service.CustomerService;
import com.neudu.yiyang.service.impl.BedTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class BedManageController {

    @Autowired
    private JSONReturn jsonReturn;

    @Autowired
    private BeddetailsService beddetailsService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private BeddetailsMapper beddetailsMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private BedTransferService bedTransferService;

    /**
     * 获取床位详情列表，支持分页和关键词搜索
     */
    @RequestMapping("get_bed_details")
    public String getBedDetails(@RequestBody Map<String, Object> requestBody) {
        Integer pageNum = (Integer) requestBody.get("pageNum");
        if (pageNum == null) {
            pageNum = 1;
        }
        Integer pageSize = (Integer) requestBody.get("pageSize");
        if (pageSize == null) {
            pageSize = 10;
        }
        String keyword = (String) requestBody.get("keyword");

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Beddetails> beds;
            if (keyword == null || keyword.trim().isEmpty()) {
                beds = beddetailsMapper.selectAll();
            } else {
                beds = beddetailsMapper.selectByKeyword(keyword);
            }
            PageInfo<Beddetails> pageInfo = new PageInfo<>(beds);
            Map<String, Object> result = new HashMap<>();
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());
            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 根据顾客 ID 获取床位详情
     */
    @RequestMapping("get_beddetails_by")
    public String getBedDetailsBy(@RequestBody Map<String, Object> requestBody) {
        try {
            Integer id = (Integer) requestBody.get("id");
            if (id == null) {
                return jsonReturn.returnError("参数 id 不能为空");
            }
            Beddetails beddetails = beddetailsService.getById(id);
            System.out.println("获取到的床位详情信息: " + beddetails);
            if (beddetails == null) {
                return jsonReturn.returnError("未找到对应的床位详情信息");
            }

            return jsonReturn.returnSuccess(beddetails);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("get_beddetails_by_customer_id")
    public String getBedDetailsByCustomerId(@RequestBody Map<String, Object> requestBody) {
        try {
            Integer customerId = (Integer) requestBody.get("customerId");
            if (customerId == null) {
                return jsonReturn.returnError("参数 customerId 不能为空");
            }
            List<Beddetails> beddetailsList = beddetailsMapper.selectByCustomerId(customerId);
            System.out.println("获取到的床位详情信息: " + beddetailsList);
            if (beddetailsList == null || beddetailsList.isEmpty()) {
                return jsonReturn.returnError("未找到对应的床位详情信息");
            }

            // 为每个 Beddetails 对象设置 bed 信息
            for (Beddetails beddetails : beddetailsList) {
                Integer bedId = beddetails.getBedId();
                Bed bed = bedMapper.selectBedById(bedId);
                beddetails.setBed(bed);
            }

            return jsonReturn.returnSuccess(beddetailsList);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 新增床位详情
     */
    @PostMapping("add_bed_details")
    public String addBedDetails(@RequestBody Beddetails beddetails) {
        try {
            System.out.println("接收到的新增床位详情数据: " + beddetails);
            // 检查顾客是否已存在于 beddetails 表中
            List<Beddetails> existingBeds = beddetailsMapper.selectByCustomerId(beddetails.getCustomerId());
            if (existingBeds != null && !existingBeds.isEmpty()) {
                System.out.println("该顾客已存在床位信息，不能重复添加");
                return jsonReturn.returnError("该顾客已存在床位信息，不能重复添加");
            }
            boolean result = beddetailsService.save(beddetails);
            if (result) {
                System.out.println("新增床位详情成功: " + beddetails);
                return jsonReturn.returnSuccess("新增床位详情成功");
            } else {
                System.out.println("新增床位详情失败，可能是床位不可用或顾客已分配床位");
                return jsonReturn.returnError("新增床位详情失败，可能是床位不可用或顾客已分配床位");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("新增床位详情出现异常: " + e.getMessage());
            return jsonReturn.returnError("新增床位详情失败：" + e.getMessage());
        }
    }

    @PostMapping("update_bed_details")
    public String updateBedDetails(@RequestBody Beddetails beddetails) throws JsonProcessingException {
        // 新增校验：id 不能为空
        System.out.println("接收到的修改床位详情数据: " + beddetails);
        if (beddetails.getId() == null) {
            return jsonReturn.returnError("参数 id 不能为空");
        }
        try {
            Beddetails existingBeddetails = beddetailsService.getById(beddetails.getId());
            if (existingBeddetails == null) {
                return jsonReturn.returnError("未找到对应的床位详情信息，无法修改");
            }
            existingBeddetails.setStartDate(beddetails.getStartDate());
            existingBeddetails.setEndDate(beddetails.getEndDate());
            existingBeddetails.setBedDetails(beddetails.getBedDetails());
            beddetailsService.updateById(existingBeddetails);
            return jsonReturn.returnSuccess("修改床位详情成功");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("修改床位详情失败：" + e.getMessage());
        }
    }


    /**
     * 获取可用顾客列表（未在 beddetails 表中的顾客）
     */
    @PostMapping("get_available_customers")
    public String getAvailableCustomers() {
        try {
            List<Customer> customers = customerMapper.getAvailableCustomers();
            return jsonReturn.returnSuccess(customers);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取可用顾客列表失败：" + e.getMessage());
        }
    }

    // 新增：获取空闲床位列表（bed_status=1）
    @PostMapping("get_available_beds")
    public String getAvailableBeds() {
        try {
            List<Bed> beds = beddetailsMapper.selectAvailableBeds(); // 自定义SQL查询空闲床位
            return jsonReturn.returnSuccess(beds);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取可用床位失败：" + e.getMessage());
        }
    }


    @PostMapping("/bed_transfer")
    public Map<String, Object> transferBed(@RequestBody Map<String, Object> request) { // 改为 Map<String, Object>
        Integer bedDetailId = (Integer) request.get("bedDetailId");
        Integer newBedId = (Integer) request.get("newBedId");

        Map<String, Object> response = new HashMap<>();

        if (bedDetailId == null || newBedId == null) {
            response.put("success", false);
            response.put("message", "参数 bedDetailId 和 newBedId 不能为空");
            return response;
        }

        String result = bedTransferService.transferBed(bedDetailId, newBedId);
        if (result.equals("床位调换成功")) {
            response.put("success", true);
            response.put("message", result);
        } else {
            response.put("success", false);
            response.put("message", result);
        }

        return response;
    }

//    @PostMapping("/swap_beds")
//    public String swapBeds(@RequestBody Map<String, Integer> swapData) {
//        Integer originalBedDetailId = swapData.get("originalBedDetailId");
//        Integer targetBedDetailId = swapData.get("targetBedDetailId");
//
//        // 参数校验
//        if (originalBedDetailId == null || targetBedDetailId == null) {
//            return jsonReturn.returnError("原床位详情ID或目标床位详情ID不能为空");
//        }
//
//        try {
//            // 获取原床位详情和目标床位详情
//            Beddetails originalDetail = beddetailsService.getById(originalBedDetailId);
//            Beddetails targetDetail = beddetailsService.getById(targetBedDetailId);
//
//            if (originalDetail == null || targetDetail == null) {
//                return jsonReturn.returnError("未找到对应的床位详情，无法对调");
//            }
//
//            // 获取原顾客和目标顾客
//            Customer originalCustomer = customerService.getById(originalDetail.getCustomerId());
//            Customer targetCustomer = customerService.getById(targetDetail.getCustomerId());
//
//            if (originalCustomer == null || targetCustomer == null) {
//                return jsonReturn.returnError("未找到对应的顾客信息，无法对调");
//            }
//
//            // 交换床位ID
//            Integer tempBedId = originalDetail.getBedId();
//            originalDetail.setBedId(targetDetail.getBedId());
//            targetDetail.setBedId(tempBedId);
//
//            // 更新床位详情表
//            beddetailsService.updateById(originalDetail);
//            beddetailsService.updateById(targetDetail);
//
//            // 更新顾客表bed_id
//            Integer tempCustomerBedId = originalCustomer.getBedId();
//            originalCustomer.setBedId(targetCustomer.getBedId());
//            targetCustomer.setBedId(tempCustomerBedId);
//
//            customerService.updateById(originalCustomer);
//            customerService.updateById(targetCustomer);
//
//
//            if (originalCustomer != null) {
//                originalCustomer.setBedId(targetDetail.getBedId());
//                customerService.updateById(originalCustomer);
//            }
//            if (targetCustomer != null) {
//                targetCustomer.setBedId(tempBedId);
//                customerService.updateById(targetCustomer);
//            }
//
//            // 更新床位状态（ 2 为占用，1 为空闲）
//            Bed originalBed = bedMapper.selectBedById(originalDetail.getBedId());
//            Bed targetBed = bedMapper.selectBedById(targetDetail.getBedId());
//
//            if (originalBed != null) {
//                originalBed.setBedStatus(2); // 标记为占用
//                bedMapper.updateByPrimaryKey(originalBed);
//            }
//            if (targetBed != null) {
//                targetBed.setBedStatus(2); // 标记为占用
//                bedMapper.updateByPrimaryKey(targetBed);
//            }
//
//            return jsonReturn.returnSuccess("床位对调成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError("床位对调失败：" + e.getMessage());
//        }
//    }


    @PostMapping("/swap_beds")
    public String swapBeds(@RequestBody Map<String, Integer> swapData) {
        Integer originalBedDetailId = swapData.get("originalBedDetailId");
        Integer targetBedDetailId = swapData.get("targetBedDetailId");

        // 参数校验
        if (originalBedDetailId == null || targetBedDetailId == null) {
            return jsonReturn.returnError("原床位详情ID或目标床位详情ID不能为空");
        }

        try {
            // 获取原床位详情和目标床位详情
            Beddetails originalDetail = beddetailsService.getById(originalBedDetailId);
            Beddetails targetDetail = beddetailsService.getById(targetBedDetailId);

            if (originalDetail == null || targetDetail == null) {
                return jsonReturn.returnError("未找到对应的床位详情，无法对调");
            }

            // 获取原顾客和目标顾客
            Customer originalCustomer = customerService.getById(originalDetail.getCustomerId());
            Customer targetCustomer = customerService.getById(targetDetail.getCustomerId());

            if (originalCustomer == null || targetCustomer == null) {
                return jsonReturn.returnError("未找到对应的顾客信息，无法对调");
            }

            // 交换床位ID
            Integer tempBedId = originalDetail.getBedId();

            // 更新Beddetails表
            originalDetail.setBedId(targetDetail.getBedId());
            targetDetail.setBedId(tempBedId);
            beddetailsService.updateById(originalDetail);
            beddetailsService.updateById(targetDetail);

            // 更新顾客表中的床位ID - 关键修复点
            Integer tempCustomerBedId = originalCustomer.getBedId();
            originalCustomer.setBedId(targetCustomer.getBedId());
            targetCustomer.setBedId(tempCustomerBedId);
            customerService.updateById(originalCustomer);
            customerService.updateById(targetCustomer);

            // 更新床位状态（2为占用，1为空闲）
            Bed originalBed = bedMapper.selectBedById(originalDetail.getBedId());
            Bed targetBed = bedMapper.selectBedById(targetDetail.getBedId());

            if (originalBed != null) {
                originalBed.setBedStatus(2); // 标记为占用
                bedMapper.updateByPrimaryKey(originalBed);
            }
            if (targetBed != null) {
                targetBed.setBedStatus(2); // 标记为占用
                bedMapper.updateByPrimaryKey(targetBed);
            }

            return jsonReturn.returnSuccess("床位对调成功");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("床位对调失败：" + e.getMessage());
        }
    }
    /**
     * 获取除指定顾客外，所有占用床位的顾客信息
     */
    @PostMapping("get_occupied_customers")
    public String getOccupiedCustomers(@RequestBody Map<String, Integer> requestBody) {
        try {
            Integer excludeCustomerId = requestBody.get("excludeCustomerId");
            if (excludeCustomerId == null) {
                return jsonReturn.returnError("参数 excludeCustomerId 不能为空");
            }
            List<Customer> occupiedCustomers = customerMapper.getOccupiedCustomers(excludeCustomerId);
            return jsonReturn.returnSuccess(occupiedCustomers);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取占用床位的顾客信息失败：" + e.getMessage());
        }
    }
}